package com.example.patient.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.example.patient.properties.WxProp;
import com.zaxxer.hikari.HikariDataSource;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;

import javax.annotation.Resource;

/**
 * 基本配置
 *
 * @Author wxy
 * @Date 2020/9/22 11:07
 * @Version 1.0
 */
@Configuration
@EnableJpaRepositories(value = {"com.example.patient.jpa"}, transactionManagerRef = "jpaTransactionManager")
public class BasicConfig {
    @Resource
    private HikariDataSource dataSource;
    @Resource
    private WxProp wxProp;

    /**
     * JPA事务管理器
     */
    @Bean("jpaTransactionManager")
    public JpaTransactionManager jpaTransactionManager() {
        JpaTransactionManager jpa = new JpaTransactionManager();
        jpa.setDataSource(dataSource);
        jpa.setRollbackOnCommitFailure(true);
        return jpa;
    }

    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder();
    }

    @Bean
    @ConditionalOnMissingBean(WxMpService.class)
    public WxMpService wxMpService(WxMpConfigStorage configStorage) {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(configStorage);
        return wxMpService;
    }

    @Bean
    @ConditionalOnMissingBean(WxMpConfigStorage.class)
    public WxMpConfigStorage wxMpConfigStorage() {
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId(wxProp.getWxPublicAppId());
        config.setSecret(wxProp.getWxPublicAppSecret());
        return config;
    }

    @Bean
    @ConditionalOnMissingBean(WxMaService.class)
    public WxMaService wxMaService(WxMaConfig wxMaConfig) {
        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(wxMaConfig);
        return wxMaService;
    }

    @Bean
    @ConditionalOnMissingBean(WxMaConfig.class)
    public WxMaConfig wxMaConfig() {
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(wxProp.getWxAppletsAppId());
        config.setSecret(wxProp.getWxAppletsAppSecret());
        return config;
    }
}
